import { Loading } from 'element-ui'
import axios from 'axios'

import router from '../router/router'

let loading = null

const service = axios.create({
  // baseURL: '',
  baseURL: window.location.href.indexOf('localhost') !== -1 ? '' : 'http://movie.fanchao.site',
  timeout: 15000, // 超时时间
  withCredentials: true, // 允许携带cookie
  headers: {
    // 'Content-Type': 'application/x-www-form-urlencoded'
  }
})

service.interceptors.request.use(config => {
  loading = Loading.service({
    lock: true,
    text: '数据处理中，请稍后...',
    background: 'rgba(255, 255, 255, 0.7)'
  })

  if (config.method === 'post') {
    config.data = config.data.params
  }
  return config
})


service.interceptors.response.use(function (res) {
  setTimeout(() => {
    loading.close();
  }, 500);
  res = res.data
  if (res.errCode && res.errCode === 401) {
    router.push('/admin/login')
  }
  return res
}, function (err) {
  setTimeout(() => {
    loading.close();
  }, 500);
  console.log(err)
})

export default service
